//
//  MerchantsListViewController.m
//  ksjv2
//
//  Created by mac on 14/12/24.
//  Copyright (c) 2014年 CnbizMedia. All rights reserved.
//

#import "MerchantsListViewController.h"
#import "Util.h"
#import "TriangleView.h"
#import "MerchantsViewController.h"
@interface MerchantsListViewController () <UITableViewDataSource,UITableViewDelegate>{
    
    UITableView*selectTable;
    UIButton*selectButton;//选择列表的黑色背景
    UIButton*typeButton;///类别按钮
    UIButton*moneyButton;///金额按钮
    UIButton*orderButton;///排序按钮
    NSMutableArray*MainSource;//当前显示数据
    NSMutableArray*selectSource;//选择列表数据
    NSMutableArray*TriangleArray;//箭头指针+
    NSMutableArray*TypeArray;///类别数据数组
    NSString*selectIndex;//当前选中的筛选列表号
    NSString*order;//排序
    NSString*T;//金额选项
    long int _page;
    NSString*slug;///目录
    BOOL isLoading;
}
@property (weak, nonatomic) IBOutlet UITableView *MainTable;
//@property (weak, nonatomic) IBOutlet UIButton *TypeButton;

@end

@implementation MerchantsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self initTable];
    [self initTriangle];
    [self loadNews];
    // Do any additional setup after loading the view.
}
-(void)loadNews{
    if(isLoading){
        [SVProgressHUD dismiss];
      return;
    }
    isLoading = YES;
    NSDictionary*parameter;
    if (T==nil) {
        parameter=@{@"p":[NSString stringWithFormat:@"%ld",_page],@"order":order,@"cateid":slug};
    }else{
        parameter=@{@"p":[NSString stringWithFormat:@"%ld",_page],@"order":order,@"t":T,@"cateid":slug};
    }
    [SVProgressHUD show];
    [[AppAPIClient sharedClient] GET:@"Jiameng/Item" parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSMutableDictionary *result = responseObject[@"data"];
        if([result isKindOfClass:[NSNull class]] || [result[@"content"] count] == 0){
            [self.MainTable reloadData];
            return;
        }
        if(MainSource == nil){
            MainSource = [[NSMutableArray alloc]initWithArray:result[@"content"] copyItems:YES];

        }else{
            for (NSDictionary*dic in result[@"content"]) {
            [MainSource addObject:dic];
            }
            
        }
        isLoading=NO;
        _page++;
        [self.MainTable reloadData];
        
//        [self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        isLoading=NO;
        NSLog(@"ERR: %@",operation.responseString);
//        isLoading = YES;
    }];
}
#pragma mark - init

-(void)initData{
    self.view.backgroundColor=UIColorFromRGB(0xf5f5f5);
    _page=1;
//    slug=@"";
//    self.title=@"";
    MainSource=[[NSMutableArray alloc]init];
    selectSource=[[NSMutableArray alloc]init];
    TriangleArray=[[NSMutableArray alloc]init];
    TypeArray=[[NSMutableArray alloc]init];
    order=@"0";
    [[AppAPIClient sharedClient] GET:@"Jiameng/Category" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        [SVProgressHUD dismiss];
        NSMutableDictionary *result = responseObject[@"data"];
        if([result isKindOfClass:[NSNull class]] || [result count] == 0){
            return;
        }
        [TypeArray addObject:@{@"name": @"全部分类",@"cateid":@""}];
        for (NSDictionary*dic in responseObject[@"data"]) {
            [TypeArray addObject:dic];
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);

    }];

}
-(void)initTriangle{
    float size= self.view.frame.size.width/3-2.5;
    for (long int i=0; i<3; i++) {
        UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundColor:[UIColor whiteColor]];
        [button setTag:i+1];
        [button setFont:[UIFont systemFontOfSize:15]];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [button setFrame:CGRectMake(size*i+2*i, 0, size, 30)];
        [button addTarget:self action:@selector(Columns:) forControlEvents:UIControlEventTouchUpInside];
        TriangleView*view1=[[TriangleView alloc]initWithFrame:CGRectMake(button.frame.size.width-15, 12.5, 5, 5)];
        [button addSubview:view1];
        [TriangleArray addObject:view1];
        [self.view addSubview:button];
        
        switch (i) {
            case 0:
                [button setTitle:@"类别" forState:UIControlStateNormal];
                typeButton=button;
//                [button setBackgroundColor:[UIColor orangeColor]];
                break;
            case 1:
                [button setTitle:@"金额" forState:UIControlStateNormal];
                moneyButton=button;
                break;
            case 2:
                [button setTitle:@"排序" forState:UIControlStateNormal];
                orderButton=button;
//                [button setBackgroundColor:[UIColor purpleColor]];
                break;
                
            default:
                break;
        }
    }
    
    
   
//    [self.view addSubview:view1];
//    [TriangleArray addObject:view1];
//    TriangleView*view2=[[TriangleView alloc]initWithFrame:CGRectMake(186, 75, 10, 10)];
//    [self.view addSubview:view2];
//    [TriangleArray addObject:view2];
//    TriangleView*view3=[[TriangleView alloc]initWithFrame:CGRectMake(298, 75, 10, 10)];
//    [self.view addSubview:view3];
//    [TriangleArray addObject:view3];
    
}

-(void)initTable{
    selectButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [selectButton setFrame:CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height-30)];
    [selectButton setBackgroundColor:[UIColor colorWithWhite:0.000 alpha:0.300]];
    [selectButton addTarget:self action:@selector(selectButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [selectButton setAlpha:0];
    [self.view addSubview:selectButton];
    
    selectTable=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 240) style:UITableViewStylePlain];
    selectTable.tag=2;
    selectTable.delegate=self;
    selectTable.dataSource=self;

    selectTable.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    [selectButton addSubview:selectTable];
    
    self.MainTable.tag=1;
    self.MainTable.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.MainTable.backgroundColor=[UIColor clearColor];
    self.MainTable.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
}
-(void)viewDidLayoutSubviews{
    self.MainTable.frame=CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height-30);
    selectTable.frame=CGRectMake(0, 0, self.view.frame.size.width, 240);
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - ButtonAction
-(void)selectButtonAction{
    if (selectButton.alpha==0) {
        [selectTable reloadData];
        [UIView animateWithDuration:.3 animations:^{
          [selectButton setAlpha:1];
        }];
        
    }else{
        [UIView animateWithDuration:.3 animations:^{
            [selectButton setAlpha:0];
        }];
        for (TriangleView*view in TriangleArray) {
            [view setIsOff:YES];
        }
        MainSource = nil;
        isLoading=NO;
        [self loadNews];
    }
    
}
- (void)Columns:(id)sender {
    UIButton*button=(UIButton*)sender;
    TriangleView*view=TriangleArray[button.tag-1];
    [view setIsOff:NO];
    selectIndex=[NSString stringWithFormat:@"%d",button.tag-1];
    if (button.tag==1) {
        NSMutableArray*array=[[NSMutableArray alloc]init];
        for (NSDictionary*dic in TypeArray) {
            [array addObject:dic[@"name"]];
        }
        selectSource=array;
    }else if (button.tag==2){
        selectSource=[@[@"不限",@"一万元以下",@"1-10万元",@"10-20万元",@"20-50万元",@"50-100万元",@"100万元以上"] mutableCopy];
    }else if (button.tag==3){
        selectSource=[@[@"智能排序",@"发布时间",@"收藏数",@"留言数"] mutableCopy];
        
    }
//    [button setTitle:selectSource[0] forState:UIControlStateNormal];
    [self selectButtonAction];
    
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag==1) {
        return MainSource.count;
    }else{
        return selectSource.count;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag==1) {
        return 75;
    }else{
      return 45;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell ;
    if(tableView.tag==1){
        cell= [tableView dequeueReusableCellWithIdentifier:@"Mcell" forIndexPath:indexPath];
    if (cell==nil) {
        
        cell=[tableView dequeueReusableCellWithIdentifier:@"Mcell"];
    }
        if(indexPath.row == [MainSource count]-2){
            [SVProgressHUD showWithStatus:@"数据加载中..." maskType:SVProgressHUDMaskTypeGradient];
            [self loadNews];
        }
        NSDictionary*dic=MainSource[indexPath.row];
        UIImageView*imageview=(UIImageView*)[cell.contentView viewWithTag:11];
        [imageview sd_setImageWithURL:[NSURL URLWithString:dic[@"thumb"]]];
        UILabel*title=(UILabel*)[cell.contentView viewWithTag:22];
        title.text=dic[@"title"];
        UILabel*comment=(UILabel*)[cell.contentView viewWithTag:44];
        comment.text=[NSString stringWithFormat:@"%@人",dic[@"comment"]];
        UILabel*description=(UILabel*)[cell.contentView viewWithTag:33];
        description.text=dic[@"description"];
        UILabel*xmtzje=(UILabel*)[cell.contentView viewWithTag:55];
        NSString *str = [dic[@"xmtzje"] stringByReplacingOccurrencesOfString:@"," withString:@"~~"];
        xmtzje.text=[NSString stringWithFormat:@"￥%@万",str];
        
    }else{
        cell= [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell==nil) {
            
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier: @"cell"];
        }
        cell.textLabel.text=selectSource[indexPath.row];
        cell.textLabel.font=[UIFont systemFontOfSize:15];
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];//点击后不会有阴影
    if (tableView.tag==1) {
        [self performSegueWithIdentifier:@"mlPmv" sender:MainSource[indexPath.row]];
    }else{
        _page=1;
        NSInteger index=[selectIndex integerValue];
        if (index==0) {
            slug=TypeArray[indexPath.row][@"cateid"];
            self.Source=TypeArray[indexPath.row][@"name"];
            [MainSource removeAllObjects];
        }else if (index==1){
            switch (indexPath.row) {
                case 0:
                    T=nil;
                    break;
                case 1:
                    T=@"1";
                    break;
                case 2:
                    T=@"1-10";
                    break;
                case 3:
                    T=@"10-20";
                    break;
                case 4:
                    T=@"20-50";
                    break;
                case 5:
                    T=@"50-100";
                    break;
                case 6:
                    T=@"100";
                    break;
                default:
                    break;
            }
            [moneyButton setTitle:@[@"不限",@"一万元以下",@"1-10万元",@"10-20万元",@"20-50万元",@"50-100万元",@"100万元以上"][indexPath.row] forState:UIControlStateNormal];
            [selectTable reloadData];
        }else if (index==2){
            order=[NSString stringWithFormat:@"%d",indexPath.row];
            [orderButton setTitle:@[@"智能排序",@"发布时间",@"收藏数",@"留言数"][indexPath.row] forState:UIControlStateNormal];
            [selectTable reloadData];
        }
        for (TriangleView*view in TriangleArray) {
           [view setIsOff:NO];
        }
        [self selectButtonAction];
    }
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    UIViewController *destination = segue.destinationViewController;
    if([destination isKindOfClass:[MerchantsViewController class]]){
        [destination setValue:sender forKey:@"Merchants_Dic"];
    }
}
-(void)setSource:(NSString *)Source{
    if (Source!=nil) {
        self.title=Source;
        [typeButton setTitle:Source forState:UIControlStateNormal];
    }
    _Source=Source;
    if (slug==nil) {
        slug=Source;
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
